package com.sinosoft.web;

import com.sinosoft.domain.DTO.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * @author loujiang
 * @date 2020/12/20 4:39 下午
 * @NOTE:
 */

@RestController
@RequestMapping("test/")
public class TestControllerV1 {

    //注入服务发现客户端
    @Autowired
    DiscoveryClient discoveryClient;
    //注入restTemplate
    @Autowired
    RestTemplate restTemplate;
    @RequestMapping("getUsers")
    public List<UserDTO> getUsers() {

        //获取当前user-center当前在线实例
        List<ServiceInstance> instances = discoveryClient.getInstances("user-center");
        //获取目标URL地址
        String trageUrl = instances.stream().
                //数据转换
                        map(instance -> instance.getUri().toString() + "/user/getAll").
                //找到第一个元素
                        findFirst().
                //如果不存在返回一异常
                        orElseThrow(() -> new IllegalArgumentException("当前没有user-center微服务实例可调用"));
        List<UserDTO> users = null;
        try {
            //调用接口
            users = restTemplate.getForObject(trageUrl, List.class);
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return users;
    }
}
